package com.zj.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seventh.common.pojo.Payload;
import com.seventh.common.pojo.R;
import com.seventh.common.utils.JwtUtils;
import com.zj.system.config.RsaKeyProperties;
import com.zj.system.mapper.LoginMapper;
import com.zj.system.pojo.entity.User;
import com.zj.system.pojo.vo.ChangePWSVo;
import com.zj.system.pojo.vo.PassWordVo;
import com.zj.system.pojo.vo.UserVo;
import com.zj.system.service.UserService;
import com.zj.system.utils.OSSUtil;
import com.zj.system.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: clms-seventh
 * @description: 用户的业务逻辑层
 * @author: 张静
 * @create: 2021-07-19 15:31
 **/
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private LoginMapper userMapper;
    @Autowired
    private RsaKeyProperties rsaKeyProperties;
    @Override
    public R sel(Integer pageSize, Integer currentPage, UserVo vo) {
        Page<User> page=new Page<>(currentPage,pageSize);
        QueryWrapper wrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(vo.getUserName())){
            wrapper.like("user_name",vo.getUserName());
        }
        if (StringUtils.isNotEmpty(vo.getLoginName())){
            wrapper.like("login_name",vo.getLoginName());
        }
        if (StringUtils.isNotEmpty(vo.getEmail())){
            wrapper.like("email",vo.getEmail());
        }
        if (StringUtils.isNotEmpty(vo.getPhone())){
            wrapper.like("phonenumber",vo.getPhone());
        }
        Page page1 = userMapper.selectPage(page, wrapper);

        return R.ok().put("records",page1.getRecords()).put("total",page1.getTotal());
    }

    @Override
    public R upStatus(Integer userId, Integer status) {
        UpdateWrapper wrapper=new UpdateWrapper();
        wrapper.eq("user_id",userId);
        wrapper.set("status",status);
        userMapper.update(null,wrapper);
        return R.ok();
    }

    @Override
    public R ins(User user) {
        User useUser = this.getToken();
        user.setCreateBy(useUser.getUserName());
        user.setCreateTime(LocalDateTime.now());
        user.setSalt("seventh");
        Md5Hash md5Hash=new Md5Hash("123456","seventh",1024);
        user.setPassword(md5Hash.toString());
        userMapper.insert(user);
        return R.ok().put("message","添加成功");
    }

    @Override
    public R up(User user) {
        User useUser = this.getToken();
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("user_name",user.getUserName());
        updateWrapper.set("login_name",user.getLoginName());
        updateWrapper.set("email",user.getEmail());
        updateWrapper.set("sex",user.getSex());
        updateWrapper.set("phonenumber",user.getPhonenumber());
        updateWrapper.set("remark",user.getRemark());
        updateWrapper.set("update_by",useUser.getUserName());
        updateWrapper.set("update_time",LocalDateTime.now());
        updateWrapper.eq("user_id",user.getUserId());
        updateWrapper.set("avatar",user.getAvatar());
        userMapper.update(null,updateWrapper);
        return R.ok().put("message","修改成功");
    }

    @Override
    public R del(Integer userId) {
        userMapper.deleteById(userId);
        return R.ok().put("message","删除成功");
    }

    @Override
    public R selById(Integer userId) {
        User user = userMapper.selectById(userId);
        return R.ok().put("userInfo",user);
    }

    @Override
    public R selUserName(User user) {
        List<User> list=userMapper.selectList(null);
        int result=0;
        for (User u:list) {
            if (user.getUserId()!=null){
                if (!u.getUserId().equals(user.getUserId())){
                   if (u.getUserName().equals(user.getUserName())){
                       result=1;
                       break;
                   }
                }
            }else {
                if (u.getUserName().equals(user.getUserName())){
                    result=1;
                    break;
                }
            }
        }
        return R.ok().put("code",result);
    }

    @Override
    public R selPhone(User user) {
        List<User> list=userMapper.selectList(null);
        int result=0;
        for (User u:list) {
            if (user.getUserId()!=null){
                if (!u.getUserId().equals(user.getUserId())){
                    if (u.getPhonenumber().equals(user.getPhonenumber())){
                        result=1;
                        break;
                    }
                }
            }else {
                if (u.getPhonenumber().equals(user.getPhonenumber())){
                    result=1;
                    break;
                }
            }
        }
        return R.ok().put("code",result);
    }

    @Override
    public R selEmail(User user) {
        List<User> list=userMapper.selectList(null);
        int result=0;
        for (User u:list) {
            if (user.getUserId()!=null){
                if (!u.getUserId().equals(user.getUserId())){
                    if (u.getEmail().equals(user.getEmail())){
                        result=1;
                        break;
                    }
                }
            }else {
                if (u.getEmail().equals(user.getEmail())){
                    result=1;
                    break;
                }
            }
        }
        return R.ok().put("code",result);
    }

    @Override
    public R upPassword(PassWordVo vo) {
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(vo.getUserName(), vo.getOldPassword());
        try{
            subject.login(usernamePasswordToken);//自动调用Realm认证器
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_name",vo.getUserName());
            Md5Hash md5Hash=new Md5Hash(vo.getNewPassword(),"seventh",1024);
            updateWrapper.set("password",md5Hash.toString());
            userMapper.update(null,updateWrapper);
            return R.ok().put("message","修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().put("message","密码错误");
        }
    }
    @Override
    public R selByUserName(String userName) {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("user_name", userName);
        List<User> users = this.userMapper.selectList(wrapper);
        return users.size() > 0 ? R.ok().put("phonenumber", users.get(0).getPhonenumber()).put("userId", users.get(0).getUserId()) : R.error();
    }
    @Override
    public R changeForgetPsw(ChangePWSVo vo) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id", vo.getUserId());
        Md5Hash md5Hash = new Md5Hash(vo.getPassword(), "seventh", 1024);
        String password = md5Hash.toString();
        updateWrapper.set("password", password);
        this.userMapper.update(null, updateWrapper);
        return R.ok().put("message", "修改成功");
    }
    private User getToken(){
        HttpServletRequest request= WebUtil.getRequest();
        String token = request.getHeader("token");
        Payload<User> info = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
        return info.getUserInfo();
    }
}
